package com.xxl.job.admin.core.alarm.impl;

import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.model.XxlJobAlarmConfig;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.core.util.alarm.LarkAlarmUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * job alarm by lark（飞书）
 *
 * @author chenlinqing
 * @description:
 * @date: 2025/8/15 17:09
 */
@Component
public class LarkJobAlarm extends JobAlarm {
    private static final Integer ALARM_TYPE = 3;
    private static Logger logger = LoggerFactory.getLogger(LarkJobAlarm.class);
    @Resource
    private LarkAlarmUtil larkAlarmUtil;

    @Override
    public void doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
        Long alarmRecordId = beforeAlarm(info, jobLog, ALARM_TYPE);
        if (alarmRecordId == null) {
            return;
        }
        XxlJobAlarmConfig config = getConfig(ALARM_TYPE);
        String executorMsg = getJobLogDetail(jobLog);
        String errorMsg = "";
        if (!StringUtils.hasLength(config.getAlarmTos())) {
            return;
        }
        String[] alarmToList = config.getAlarmTos().split(",");
        for (String alarmTo : alarmToList) {
            try {

                larkAlarmUtil.sendMessage(config.getAlarmTitle(), alarmTo, info.getExecutorHandler(),
                        info.getJobDesc(), StringUtils.hasLength(executorMsg) ? executorMsg : jobLog.getHandleMsg());
            } catch (Exception e) {
                errorMsg = errorMsg + e.getMessage();
            }
        }
        if (!StringUtils.hasLength(errorMsg)) {
            afterAlarm(alarmRecordId, 2, null);
        } else {
            afterAlarm(alarmRecordId, 3, errorMsg);
        }
    }
}
